<template>
  <div class="app-container">
    <el-form class="basic-form" ref="form" :model="form" label-width="80px" :rules="rules">
      <el-row>
        <el-col :span="6">
<!--          <el-form-item label="新闻封面" prop="cover">-->
<!--            <SingleImageUpload v-model="form.cover" />-->
<!--          </el-form-item>-->
        </el-col>
        <el-col>
          <el-form-item label="服务标题" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="服务概要" prop="summary">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.summary" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="服务内容" prop="content" required>
        <tinymce ref="tinymce" v-model="form.content" :height="300" />
      </el-form-item>

      <el-form-item>
        <el-button v-waves type="primary" @click="handleSubmit(form)">提交</el-button>
      <el-button v-waves @click="handleReset()">重置</el-button>
  </el-form-item>
</el-form>
  </div>
  </template>
<script>
import Tinymce from '@/components/Tinymce';
import SingleImageUpload from '@/components/Upload/SingleImage';
import waves from '@/directive/waves';
import * as homeHttp from '@/api/home';

export default {
  name: 'news-edit',
  components: { Tinymce, SingleImageUpload },
  directives: { waves },
  data() {
    return {
      language: 'zh_CN',
      form: {},
      rules: {
        name: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
        summary: [{ required: true, message: '请输入新闻概要', trigger: 'blur' }],
        content: [{ required: true, message: '请输入新闻内容', trigger: 'change' }],
        cover: [{ required: true, message: '请上传封面图', trigger: 'change' }]
      }
    }
  },
  created() {
    const { id } = this.$route.params;

    if (id) {
      this.getData(id);
    }
  },
  methods: {
    handleSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false;

        try {
          const res = await homeHttp.submitNews(this.form);

          if (!res.data.Data) throw new Error('上传失败');

          this.$router.push('/news');
        } catch(e) {
          console.log('news-center/edit: ', e);
          this.$message.error('提交失败');
        }
      });
    },
    handleReset() {
      this.$refs['form'].resetFields();
      this.$refs['tinymce'].setContent('');
    },

    // 获取文章内容
    async getData(id) {
      const res = await homeHttp.getNewsById({ id });
      this.form = res && res.data && res.data.Data || {};
    }
  }
}
</script>
